package cn.itsource.ymcc.listener;

import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.dto.PayDto;
import cn.itsource.ymcc.service.ICourseOrderService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;


@Component
//添加监听
@RocketMQTransactionListener(
        txProducerGroup="service-order-producer"
)
@Slf4j
public class CourseOrderRocketMqListener implements RocketMQLocalTransactionListener {
    @Autowired
    private ICourseOrderService courseOrderService;
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        //保存主订单和子订单
        if(o==null){
            //参数都没有，直接回滚
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        try {
            CourseOrder courseOrder=(CourseOrder) o;
            courseOrderService.saveOrderItems(courseOrder);
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;//执行本地事务失败
        }
        //成功
        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        // 根据消息体去查询本地事务是否已经执行成功
        // byte[] --> jsonString   -->PayDto 对象
        log.info("检查本地事务状态");
        try {
            byte[] bytOjb = (byte[])message.getPayload();
            String messgeStr = new String(bytOjb, StandardCharsets.UTF_8);
            PayDto payDto = JSONObject.parseObject(messgeStr, PayDto.class);
            CourseOrder courseOrder = courseOrderService.selectOrderByOrderNo(payDto.getOrderNo());
            return courseOrder == null?RocketMQLocalTransactionState.ROLLBACK:RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }

    }
}
